package io.github.talelin.latticy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.talelin.latticy.mapper.CUserMapper;
import io.github.talelin.latticy.mapper.UserAuditMapper;
import io.github.talelin.latticy.model.CUserDO;
import io.github.talelin.latticy.model.UserAuditDO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UserAuditVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户审核服务
 * @作者 xiaohengheng
 * @微信公号 林间有风
 * @开源项目 $ http://7yue.pro
 * @免费专栏 $ http://course.7yue.pro
 * @我的课程 $ http://imooc.com/t/4294850
 * @创建时间 2024-01-15
 */
@Service
public class UserAuditService {

    @Autowired
    private UserAuditMapper userAuditMapper;
    
    @Autowired
    private CUserMapper cUserMapper;

    /**
     * 获取待审核列表
     */
    public PageResponseVO<UserAuditVO> getPendingAudits(Long page, Long count) {
        Page<UserAuditDO> pager = new Page<>(page, count);
        QueryWrapper<UserAuditDO> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "pending");
        wrapper.orderByDesc("create_time");
        
        Page<UserAuditDO> result = userAuditMapper.selectPage(pager, wrapper);
        
        List<UserAuditVO> userAuditVOs = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return new PageResponseVO<>(result.getTotal(), userAuditVOs, page, count);
    }

    /**
     * 获取审核列表
     */
    public PageResponseVO<UserAuditVO> getAuditList(Long page, Long count, String status, String keyword) {
        Page<UserAuditDO> pager = new Page<>(page, count);
        QueryWrapper<UserAuditDO> wrapper = new QueryWrapper<>();
        
        if (StringUtils.hasText(status)) {
            wrapper.eq("status", status);
        }
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("auditor_name", keyword)
                    .or()
                    .like("merchant_name", keyword));
        }
        
        wrapper.orderByDesc("create_time");
        
        Page<UserAuditDO> result = userAuditMapper.selectPage(pager, wrapper);
        
        List<UserAuditVO> userAuditVOs = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return new PageResponseVO<>(result.getTotal(), userAuditVOs, page, count);
    }

    /**
     * 获取审核详情
     */
    public UserAuditVO getAuditDetail(Long id) {
        UserAuditDO userAudit = userAuditMapper.selectById(id);
        if (userAudit == null) {
            throw new RuntimeException("审核记录不存在");
        }
        return convertToVO(userAudit);
    }

    /**
     * 审核通过
     */
    public void approveAudit(Long id, String remark) {
        UserAuditDO userAudit = userAuditMapper.selectById(id);
        if (userAudit == null) {
            throw new RuntimeException("审核记录不存在");
        }
        
        if (!"pending".equals(userAudit.getStatus())) {
            throw new RuntimeException("该记录已审核，不能重复审核");
        }
        
        // 更新审核记录状态
        userAudit.setStatus("approved");
        userAudit.setAuditRemark(remark);
        userAudit.setAuditTime(LocalDateTime.now());
        // TODO: 设置审核人信息
        
        userAuditMapper.updateById(userAudit);
        
        // 审核通过后，将收款码更新到用户表
        this.updateUserBankQrCode(userAudit.getUserId(), userAudit.getBankQrcodeUrl());
    }

    /**
     * 审核拒绝
     */
    public void rejectAudit(Long id, String remark) {
        UserAuditDO userAudit = userAuditMapper.selectById(id);
        if (userAudit == null) {
            throw new RuntimeException("审核记录不存在");
        }
        
        if (!"pending".equals(userAudit.getStatus())) {
            throw new RuntimeException("该记录已审核，不能重复审核");
        }
        
        userAudit.setStatus("rejected");
        userAudit.setAuditRemark(remark);
        userAudit.setAuditTime(LocalDateTime.now());
        // TODO: 设置审核人信息
        
        userAuditMapper.updateById(userAudit);
    }

    /**
     * 获取审核统计
     */
    public Map<String, Object> getAuditStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 统计各状态数量
        QueryWrapper<UserAuditDO> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.eq("status", "pending");
        long pendingCount = userAuditMapper.selectCount(pendingWrapper);
        
        QueryWrapper<UserAuditDO> approvedWrapper = new QueryWrapper<>();
        approvedWrapper.eq("status", "approved");
        long approvedCount = userAuditMapper.selectCount(approvedWrapper);
        
        QueryWrapper<UserAuditDO> rejectedWrapper = new QueryWrapper<>();
        rejectedWrapper.eq("status", "rejected");
        long rejectedCount = userAuditMapper.selectCount(rejectedWrapper);
        
        stats.put("pending", pendingCount);
        stats.put("approved", approvedCount);
        stats.put("rejected", rejectedCount);
        stats.put("total", pendingCount + approvedCount + rejectedCount);
        
        System.out.println("统计结果: " + stats);
        
        return stats;
    }

    /**
     * 批量审核通过
     */
    public void batchApproveAudits(List<Long> ids) {
        for (Long id : ids) {
            approveAudit(id, "批量审核通过");
        }
    }

    /**
     * 批量审核拒绝
     */
    public void batchRejectAudits(List<Long> ids, String remark) {
        for (Long id : ids) {
            rejectAudit(id, remark);
        }
    }

    /**
     * 转换为VO
     */
    private UserAuditVO convertToVO(UserAuditDO userAudit) {
        UserAuditVO vo = new UserAuditVO();
        vo.setId(userAudit.getId());
        vo.setUserId(userAudit.getUserId());
        vo.setMerchantName(userAudit.getMerchantName());
        
        // 设置收款码URL，如果为空则设置测试URL
        String qrcodeUrl = userAudit.getBankQrcodeUrl();
        if (qrcodeUrl == null || qrcodeUrl.trim().isEmpty()) {
            qrcodeUrl = "https://via.placeholder.com/200x200/4CAF50/FFFFFF?text=测试收款码";
        }
        vo.setBankQrcodeUrl(qrcodeUrl);
        
        vo.setStatus(userAudit.getStatus());
        vo.setStatusText(getStatusText(userAudit.getStatus()));
        vo.setAuditRemark(userAudit.getAuditRemark());
        vo.setAuditTime(userAudit.getAuditTime());
        vo.setAuditorId(userAudit.getAuditorId());
        vo.setAuditorName(userAudit.getAuditorName());
        vo.setCreateTime(userAudit.getCreateTime());
        vo.setUpdateTime(userAudit.getUpdateTime());
        
        // 设置默认用户信息（后续可以关联用户表获取真实信息）
        vo.setUserNickname("用户" + userAudit.getUserId());
        vo.setUserAvatar(""); // 可以设置默认头像
        
        return vo;
    }

    /**
     * 更新用户收款码
     */
    private void updateUserBankQrCode(Long userId, String bankQrcodeUrl) {
        if (userId == null || bankQrcodeUrl == null || bankQrcodeUrl.trim().isEmpty()) {
            System.out.println("更新用户收款码失败：用户ID或收款码URL为空");
            return;
        }
        
        try {
            // 查询用户是否存在
            CUserDO user = cUserMapper.selectById(userId);
            if (user == null) {
                System.out.println("更新用户收款码失败：用户不存在，用户ID: " + userId);
                return;
            }
            
            // 更新用户的收款码
            user.setBankQrCode(bankQrcodeUrl);
            int result = cUserMapper.updateById(user);
            
            if (result > 0) {
                System.out.println("用户收款码更新成功，用户ID: " + userId + ", 收款码: " + bankQrcodeUrl);
            } else {
                System.out.println("用户收款码更新失败，用户ID: " + userId);
            }
        } catch (Exception e) {
            System.err.println("更新用户收款码时发生异常，用户ID: " + userId + ", 错误: " + e.getMessage());
        }
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(String status) {
        switch (status) {
            case "pending":
                return "待审核";
            case "approved":
                return "已通过";
            case "rejected":
                return "已拒绝";
            default:
                return "未知状态";
        }
    }
} 